package com.freedom.web.mymvc.pool;

import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.freedom.web.mymvc.handler.HttpUserHandler;
import com.freedom.web.mymvc.route.MyRoute;
import com.freedom.web.mymvc.route.Route;
import com.freedom.web.mymvc.utils.LoggerUtils;
import com.freedom.web.mymvc.utils.NettyUtils;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;

public class MyMVCRunnable implements Runnable {
	// logger
	private static final Logger logger = LogManager.getLogger(MyMVCRunnable.class);
	// 保存变量
	private ChannelHandlerContext context;
	private FullHttpRequest request;
	private FullHttpResponse response;

	public MyMVCRunnable(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse resp) {
		context = ctx;
		request = req;
		response = resp;
	}

	@Override
	public void run() {
		// 当前在第3层的线程池里
		// 根据URI来查找object.method.invoke
		String uri = request.getUri();
		// 1)规整化,必要的话去掉第1个"?"
		int index = uri.indexOf("?");
		if (-1 != index) {
			uri = uri.substring(0, index);
		}
		LoggerUtils.debug(logger, "uri---" + uri + " length:" + uri.length());
		// 2)寻找路由失败
		Route route = MyRoute.getInstance().getRoute(uri);
		if (null == route) {
			request = null;
			response = null;
			NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND);
			return;
		}
		// 3)寻找路由成功了
		Object obj = route.getObject();
		Method method = route.getMethod();
		try {
			method.invoke(obj, request, response);
			// http://www.cnblogs.com/Binhua-Liu/p/5295365.html
			// 根据此文章，线程安全，所以可以直接写
			LoggerUtils.debug(logger, "context---" + context);
			// 目前都是保持短连接,用于APP服务器没有问题
			context.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			LoggerUtils.error(logger, e.toString());
			request = null;
			response = null;
			NettyUtils.sendError(context, HttpResponseStatus.SERVICE_UNAVAILABLE);
			return;
		}
		// 结束
	}

}
